<template>
  <div class="online-edit-form">
    <van-nav-bar class="header"
      left-arrow
      @click-left="onBack()"
    >
      <template #title>
        <p style="font-size: 16px;color: #333333;font-weight: 400;">{{form.formName}}</p>
      </template>
      <template #left>
        <van-icon name="arrow-left" size="18" color="#3B3938" />
      </template>
    </van-nav-bar>
    <van-form class="main-box" ref="form" style="overflow: auto;"
      :label-width="(form.labelWidth || 100) + 'px'"
      label-align="left"
    >
      <online-custom-block :widgetList="form.widgetList" />
    </van-form>
    <van-row class="menu-box" type="flex" justify="space-between" align="center">
      <van-button size="normal" style="width: 104px; height: 40px;" @click="onBack()">取消</van-button>
      <van-button size="normal" style="width: 100%; margin-left: 8px; height: 40px;" color="#FF7700" @click="onSubmit()">保存</van-button>
    </van-row>
    <!-- 弹出子表单 -->
    <van-popup
      v-if="showSubPage"
      v-model="showSubPage"
      position="right"
      get-container="body"
      :overlay="false"
      style="height: 100vh; width: 100vw; background: #F6F6F6;"
    >
      <online-form :formId="subFormId" :rowData="editRowData" @close="onCloseSubForm" :saveData="false"  />
    </van-popup>
  </div>
</template>

<script>
import { Notify } from 'vant';
import { OnlineFormMixins } from './onlineFormMixins.js';

export default {
  name: 'onlineEditForm',
  props: {
    formConfig: {
      type: Object
    },
    // 主表数据
    masterTableData: {
      type: Object
    },
    // 需要编辑数据，如果是null则是新增
    rowData: {
      type: Object
    },
    // 是否保存到数据库
    saveData: {
      type: Boolean,
      default: true
    },
    isCopy: {
      type: Boolean,
      default: false
    }
  },
  mixins: [OnlineFormMixins],
  provide () {
    return {
      form: () => {
        return {
          ...this.form,
          getDictDataList: this.getDictDataList,
          getWidgetValue: this.getWidgetValue,
          getWidgetVisible: this.getWidgetVisible,
          onValueChange: this.onValueChange,
          onWidgetValueChange: this.onWidgetValueChange,
          getDropdownParams: this.getDropdownParams,
          masterTable: this.masterTable,
          handlerOperation: this.handlerOperation,
          checkOperationVisible: this.checkOperationVisible,
          getPrimaryData: this.getPrimaryData,
          formData: this.formData,
          rules: this.rules
        }
      }
    }
  },
  methods: {
    onBack (refresh = false, data) {
      this.$emit('close', refresh, data);
    },
    onCloseSubForm (refresh, data) {
      if (refresh && this.operationCallback) {
        this.operationCallback(data);
      }
      this.showSubPage = false;
      if (refresh) this.onRefresh();
    },
    async onSaveFormData () {
      if (this.masterTable == null || this.masterTable.datasource == null) {
        Notify({ type: 'danger', message: '表单使用主数据源或主表不存在！' });
        throw new Error('表单使用主数据源或主表不存在！');
      }
      let params = {
        datasourceId: this.masterTable.datasource.datasourceId,
        relationId: (this.masterTable.relation || {}).relationId,
        masterData: this.isRelation ? undefined : this.formData[this.masterTable.datasource.variableName]
      }
      if (this.isRelation) {
        // 从表数据添加或更新
        params.slaveData = {
          ...this.formData[this.masterTable.relation.variableName]
        }
        // 设置关联字段的值
        let slaveColumnValue = (this.masterTableData || {})[this.masterTable.relation.masterColumn.columnName];
        if (slaveColumnValue != null) {
          params.slaveData[this.masterTable.relation.slaveColumn.columnName] = slaveColumnValue;
        }
      } else {
        // 设置一对多从表数据
        params.slaveData = this.tableWidgetList.reduce((retObj, widget) => {
          if (widget.relation != null) {
            retObj[widget.relation.variableName] = this.formData[widget.relation.variableName];
          }
          return retObj;
        }, {});
      }

      // 执行提交数据前脚本
      if (typeof this.form.eventInfo[this.OnlineFormEventType.BEFORE_COMMIT_FORM_DATA] === 'function') {
        params = await this.form.eventInfo[this.OnlineFormEventType.BEFORE_COMMIT_FORM_DATA](params);
      }

      if (params == null) {
        throw new Error('取消保存数据');
      }

      // 把slaveData里的relationVariableName替换成relationId
      if (!this.isRelation && params.slaveData) {
        let slaveDataKeyList = Object.keys(params.slaveData);
        if (slaveDataKeyList.length > 0) {
          let relationVariableNameMap = new Map();
          this.form.tableMap.forEach(table => {
            if (table.relation != null) {
              relationVariableNameMap.set(table.relation.variableName, table.relation.relationId);
            }
          });
          slaveDataKeyList.forEach(key => {
            let relationId = relationVariableNameMap.get(key);
            if (relationId != null) {
              params.slaveData[relationId] = params.slaveData[key];
            }
            params.slaveData[key] = undefined;
          });
        }
      }

      let commitUrl;
      if (this.isRelation) {
        // 从表提交数据
        commitUrl = (this.rowData == null || this.isCopy) ? '/admin/online/onlineOperation/addOneToManyRelation/' : '/admin/online/onlineOperation/updateOneToManyRelation/';
      } else {
        // 主表提交数据
        commitUrl = (this.rowData == null || this.isCopy) ? '/admin/online/onlineOperation/addDatasource/' : '/admin/online/onlineOperation/updateDatasource/';
      }
      commitUrl += this.masterTable.datasource.variableName;
      await this.doUrl(commitUrl, 'post', params);
      Notify({ type: 'success', message: '保存成功！' });
      this.onBack(true);
    },
    // 提交
    onSubmit () {
      if (Array.isArray(this.richEditWidgetList)) {
        this.richEditWidgetList.forEach(richWidget => {
          if (richWidget && richWidget.widgetImpl) {
            this.onValueChange(richWidget, richWidget.widgetImpl.getHtml());
          }
        });
      }
      this.$refs.form.validate().then(async res => {
        if (this.saveData) {
          // 非级联保存数据
          this.onSaveFormData();
        } else {
          // 级联添加返回表单数据到父表单
          let data = null;
          if (this.isRelation) {
            data = this.formData[this.masterTable.relation.variableName];
          }
          if (typeof this.form.eventInfo[this.OnlineFormEventType.BEFORE_COMMIT_FORM_DATA] === 'function') {
            data = await this.form.eventInfo[this.OnlineFormEventType.BEFORE_COMMIT_FORM_DATA](data);
          }
          this.onBack(true, data);
        }
      }).catch(e => {});
    },
    getTableData (widget) {
      return widget.relation ? this.formData[widget.relation.variableName] : [];
    },
    setTableData (widget, dataList) {
      if (widget == null) return;
      if (widget.relation) {
        this.formData[widget.relation.variableName] = dataList;
      }
    },
    async loadRelationTableData (widget) {
      try {
        if (widget == null || widget.datasource == null || widget.relation == null) return;

        let params = {
          datasourceId: widget.datasource.datasourceId,
          relationId: widget.relation.relationId,
          filterDtoList: [
            {
              tableName: widget.table.tableName,
              columnName: widget.relation.slaveColumn.columnName,
              filterType: this.SysOnlineColumnFilterType.EQUAL_FILTER,
              columnValue: (this.formData[widget.datasource.variableName] || {})[widget.relation.masterColumn.columnName]
            }
          ]
        }
        // 脱敏设置
        params.ignoreMaskFields = this.getIgnoreMaskFields(widget);
        if (typeof widget.eventInfo[this.OnlineFormEventType.BEFORE_LOAD_TABLE_DATA] === 'function') {
          params = await widget.eventInfo[this.OnlineFormEventType.BEFORE_LOAD_TABLE_DATA](params);
        }
        if (params == null) {
          throw new Error('取消加载数据');
        }
        let res = await this.doUrl('/admin/online/onlineOperation/listByOneToManyRelationId/' + widget.datasource.variableName, 'post', params);

        if (typeof widget.eventInfo[this.OnlineFormEventType.AFTER_LOAD_TABLE_DATA] === 'function') {
          res.data.dataList = await widget.eventInfo[this.OnlineFormEventType.AFTER_LOAD_TABLE_DATA](res.data.dataList);
        }
        // 复制数据，清空主键id以及自动编码字段
        if (this.isCopy) {
          let temp = new Date().getTime();
          let autoCodeColumnName = [];
          if (widget.table && Array.isArray(widget.table.columnList)) {
            widget.table.columnList.forEach(column => {
              if (column.fieldKind === this.SysOnlineFieldKind.AUTO_CODE) {
                autoCodeColumnName.push(column.columnName);
              }
            });
          }
          res.data.dataList.forEach(item => {
            if (widget.primaryColumnName) item[widget.primaryColumnName] = undefined;
            item.__cascade_add_id__ = temp++;
            autoCodeColumnName.forEach(columnName => {
              item[columnName] = undefined;
            });
          });
        }
        this.formData[widget.relation.variableName] = res.data.dataList;
        return res.data.dataList;
      } catch (e) {
        console.log(e);
        throw e;
      }
    },
    clearFormData (data, columnList) {
      if (data == null || !Array.isArray(columnList)) return;
      columnList.forEach(columnName => {
        data[columnName] = undefined;
      });
    },
    initFormData () {
      if (this.rowData != null) {
        return new Promise((resolve, reject) => {
          // 如果是复制，清空主键以及自动编码字段
          let clearColumnList = [];
          if (this.isCopy && this.masterTable && Array.isArray(this.masterTable.columnList)) {
            this.masterTable.columnList.forEach(column => {
              if (column.primaryKey || column.fieldKind === this.SysOnlineFieldKind.AUTO_CODE) {
                clearColumnList.push(column.columnName);
              }
            });
          }
          if (this.isRelation) {
            this.formData[this.masterTable.relation.variableName] = {
              ...this.rowData
            }
            this.clearFormData(this.formData[this.masterTable.relation.variableName], clearColumnList);
            resolve();
          } else {
            // 初始化主表以及一对一字段数据
            let relationNameList = [];
            let datasourceName;
            this.form.tableMap.forEach(table => {
              if (table.relation && table.relation.relationType === this.SysOnlineRelationType.ONE_TO_ONE) {
                relationNameList.push(table.relation.variableName);
              } else if (table.relation == null) {
                datasourceName = table.datasource.variableName;
              }
            });
            Object.keys(this.rowData).forEach(key => {
              if (relationNameList.indexOf(key) === -1) {
                // 主表字段
                this.formData[datasourceName][key] = this.rowData[key];
              } else {
                // 从表字段
                if (this.rowData[key]) this.formData[key] = this.rowData[key];
              }
            });
            // 初始化一对多数据
            if (Array.isArray(this.tableWidgetList) && this.tableWidgetList.length > 0) {
              try {
                let httpCallList = this.tableWidgetList.map(widget => {
                  if (widget.relation && widget.relation.relationType === this.SysOnlineRelationType.ONE_TO_MANY) {
                    return this.loadRelationTableData(widget);
                  }
                  return null;
                }).filter(item => item != null);
                Promise.all(httpCallList).then(res => {
                  this.clearFormData(this.formData[datasourceName], clearColumnList);
                  resolve();
                }).catch(e => {
                  console.log(e);
                  this.clearFormData(this.formData[datasourceName], clearColumnList);
                  reject(e);
                });
              } catch (e) {
                console.log(e);
              }
            } else {
              this.clearFormData(this.formData[datasourceName], clearColumnList);
              resolve();
            }
          }
        });
      } else {
        return Promise.resolve();
      }
    }
  },
  computed: {
    form () {
      let temp = this.buildFormConfig(this.formConfig);
      return temp;
    }
  },
  created () {
    this.isReady = false;
    this.initPage();
    this.initFormWidgetList();
    this.initWidgetRule();
    if (typeof this.form.eventInfo[this.OnlineFormEventType.AFTER_CREATE_FORM] === 'function') {
      this.form.eventInfo[this.OnlineFormEventType.AFTER_CREATE_FORM]();
    }
    this.initFormData().then(() => {
      if (typeof this.form.eventInfo[this.OnlineFormEventType.AFTER_LOAD_FORM_DATA] === 'function') {
        this.form.eventInfo[this.OnlineFormEventType.AFTER_LOAD_FORM_DATA]();
      }
      this.initWidgetLinkage();
    }).catch(e => {
      console.log(e);
    });
    this.isReady = true;
  }
};
</script>

<style scoped>
  .online-edit-form {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background: #F6F7F9;
  }
  .main-box {
    background: #F6F7F9;
    flex-grow: 1;
    flex-shrink: 1;
    height: 100px;
  }
  .menu-box {
    flex-grow: 0;
    flex-shrink: 0;
    width: 100%;
    padding: 15px 16px;
    flex-wrap: nowrap;
    background: white;
    box-sizing: border-box;
    margin-top: 16px;
  }
</style>
